package com.kang.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.kang.pojo.Jurisdiction;
import com.kang.service.JurisdictionService;

/**
 * 基本控制层，用于从session获取用户信息并验证权限
 * 
 * @author zs614
 *
 */
public class Controller {
	/**
	 * 保存当前用户所有权限
	 */
	private List<Jurisdiction> userRight;
	/**
	 * 保存当前用户所有cookie
	 */
	protected Map<String, Cookie> cookieMap;
	/**
	 * 当前用户ID
	 */
	protected int userID;

	/**
	 * 用户权限服务层
	 */
	@Resource
	private JurisdictionService rightService;
	/**
	 * 检查用户权限有该权限时返回
	 */
	public static final Integer SUCCESS = 1;
	/**
	 * 检查用户没有权限时返回
	 */
	public static final Integer LIMIT = 2;
	/**
	 * 检查用户有权限但该权限被关闭返回
	 */
	public static final Integer CLOSE = 3;

	/**
	 * 初始化用户权限
	 * 
	 * @param session
	 */
	public void initRight(HttpSession session) {
		userID = (Integer) session.getAttribute("userID");
		userRight = rightService.listUserJurisdiction((Integer) session.getAttribute("userID"));
	}

	/**
	 * 根据权限名称判断用户是否有该权限
	 * 
	 * @param right
	 * @return
	 */
	public Integer checkRight(String right) {
		for (Jurisdiction j : userRight) {
			if (j == null)
				continue;
			if (j.getJurisdictionname() != null && right.equals(j.getJurisdictionname())) {
				if ("关闭".equals(j.getStatus())) {
					return CLOSE;
				}
				return SUCCESS;
			}
		}
		return LIMIT;
	}

	/**
	 * 获取该用户所有cookie，并保存到map中
	 * 
	 * @param request
	 * @return
	 */
	public Map<String, Cookie> readCookieMap(HttpServletRequest request) {
		cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}

	public List<Jurisdiction> getUserRight() {
		return userRight;
	}

	public void setUserRight(List<Jurisdiction> userRight) {
		this.userRight = userRight;
	}

	public Integer getUserID() {
		return userID;
	}

	public void setUserID(Integer userID) {
		this.userID = userID;
	}

}
